const mysql = require('mysql2');

let MysqlServer = {
    connection: null,
    state: 0 // 0.未连接 1.正在连接 2.已连接 3.正在重连 4. 连接异常(不再重连)
};

function SelectLocalData() {
    if(MysqlServer.connection && MysqlServer.state === 2) {
        MysqlServer.connection.query('SELECT * FROM `user` LIMIT 10', (err, results) => {
            if (err) {
                console.log("query error",err.message);
                return
            }
            console.log("query success: ",results.length, new Date());
        });
    }
}

function handleConnect() {
  MysqlServer.connection = mysql.createConnection({
    host: '192.168.1.222',
    user: 'root',
    password: 'root',
    database: 'configuration',
    port: 3306,
  });

  MysqlServer.connection.connect((err) => {
    if (!err) {
        MysqlServer.state = 2
        console.log('✅ 成功连接到数据库 - threadId:', MysqlServer.connection.threadId);
    } 
  });

  // 监听错误事件
  MysqlServer.connection.on('error', (err) => {
    // return
    MysqlServer.state = 3
    if (err.code === 'ECONNREFUSED') {
      // 如果是连接丢失，手动重连
      console.log('连接失败，正在尝试重新连接...');
      setTimeout(handleConnect, 3000);
    } else if (err.code === 'PROTOCOL_CONNECTION_LOST') {
      // 如果是连接丢失，手动重连
      console.log('连接丢失，正在尝试重新连接...');
      setTimeout(handleConnect, 3000);
    } else if(err.code === 'ECONNRESET') {
        console.log('连接被重置，正在尝试重新连接...');
      setTimeout(handleConnect, 3000);
    }else {
      // 其他错误可以抛出或处理
    //   throw err;
        MysqlServer.state = 4
      console.log("未知错误",err.code)
    }
  });

  // 监听连接关闭事件
//   connection.on('close', () => {
//     console.warn('⚠️ 数据库连接已关闭，尝试重连...');
//     setTimeout(handleConnect, 3000);
//   });
}

// 初始启动连接
handleConnect();

setInterval(SelectLocalData, 3000)
/*
const insertQuery = "INSERT INTO users (name, age) VALUES (?, ?)";
  const values = ['张三', 25];

  connection.query(insertQuery, values, (error, results, fields) => {
    if (error) throw error;

    console.log('插入的记录ID:', results.insertId); // 新插入行的行 ID
  });
*/
